package com.rinlink.jbcodec.common;

import com.alibaba.fastjson.JSONObject;
import com.rinlink.jbcodec.JSONCodec;
import com.rinlink.jbcodec.exception.AttributePropertyException;
import com.rinlink.jbcodec.exception.FieldValueException;

public class CreatorUtils {

    public static <T> T getAttrOrException(JSONObject attr,Class<T> cls,String name){
        T v = attr.getObject(name,cls);
        if (v == null){
            throw new AttributePropertyException(name);
        }
        return v;
    }

    public static <T> T getValueOrException(JSONObject data,Class<T> cls,String name){
        T v = data.getObject(name,cls);
        if (v == null){
            throw new FieldValueException(name);
        }
        return v;
    }

    public final static String getBytesField(JSONObject attr){
        return getAttrOrException(attr,String.class,"bytes_field");
    }

    public final static JSONCodec.Scheme getScheme(JSONObject attr){
        return getAttrOrException(attr, JSONCodec.Scheme.class,"scheme");
    }

    public final static String getListSizeField(JSONObject attr){
        return getAttrOrException(attr,String.class,"list_size_field");
    }

    public final static int getListSize(JSONObject attr,JSONObject data){
        String field = getListSizeField(attr);
        return getValueOrException(data,Integer.class,field);
    }

    public final static int getArraySize(JSONObject attr){
        return getAttrOrException(attr,Integer.class,"array_size");
    }

    public final static int getBytes(JSONObject attr){
        return getAttrOrException(attr,Integer.class,"bytes");
    }

    public final static int getBytes(JSONObject attr,JSONObject data){
        String field = getBytesField(attr);
        return getValueOrException(data,Integer.class,field);
    }
}
